<?php

namespace App\Models\Applet\Order;

use App\Models\Applet\Sponsor\BaseSponsorModel;

class SponsorMasterOrderModel extends BaseSponsorModel
{
    protected $table = 'sponsor_master_orders';

    const ORDER_STATUS_SUCCESS   = 30; // 已支付
    const ORDER_STATUS_COMPLETED = 60; // 已完成

    const PAY_STATUS_SUCCESS = 20; // 已支付

    const PAY_TYPE_WECHAT   = 10; // 微信支付
    const PAY_TYPE_ALIPAY   = 20; // 支付宝
    const PAY_TYPE_INTEGRAL = 30; // 积分

    /**
     * 根据订单号获取订单信息
     * @param string $orderNo
     * @param array $fields
     * @return array
     */
    public function getItemByOrderNo(string $orderNo, array $fields = self::QUERY_DEFAULT_FIELDS): array
    {
        $result = $this->select($fields)
                       ->where(['order_no' => $orderNo])
                       ->first();
        return $result ? $result->toArray() : [];
    }

    /**
     * 订单列表
     * @param array $params
     * @param array $fields
     * @return array
     */
    public function list(array $params, array $fields = self::QUERY_DEFAULT_FIELDS): array
    {
        $query = $this->select($fields)
                      ->join('sponsor_orders', 'sponsor_orders.order_master_id', '=', 'sponsor_master_orders.id');
        if (!empty($params['orderStatus'])) {
            $query = $query->where('sponsor_orders.order_status', $params['orderStatus']);
        }

        if (!empty($params['payStatus'])) {
            $query = $query->where('pay_status', $params['payStatus']);
        }

        return $query->where('user_id', $params['userId'])
                     ->where('sponsor_orders.deleted', self::DELETED_NO)
                     ->orderBy('id', 'desc')
                     ->offset((CURRENT_PAGE - 1) * PAGE_SIZE)
                     ->limit(PAGE_SIZE)
                     ->get()
                     ->toArray();
    }

    /**
     * 根据用户id获取总条数
     * @param int $userId
     * @return int
     */
    public function getTotalByUserId(int $userId): int
    {
        return $this->leftJoin('sponsor_orders', 'sponsor_orders.order_master_id', '=', 'sponsor_master_orders.id')
                    ->where('user_id', $userId)
                    ->where('sponsor_orders.deleted', self::DELETED_NO)
                    ->count();
    }

    /**
     * @return void
     */
    public function getItemByIdAndDeletedAll(int $id, $fields = self::QUERY_DEFAULT_FIELDS): array
    {
        $result = $this->select($fields)
                       ->where('id', $id)
                       ->first();
        return $result ? $result->toArray() : [];
    }
}
